<template>
	<div class="auditer">
		<div class="input">
			<slot :names="valueName" :open="open" :list="checkList">
				<el-input @click.native="open" type="text" clearable :value="valueName" readonly suffix-icon="el-icon-user" />
			</slot>
		</div>
		<el-dialog
			:visible.sync="visible"
			append-to-body
			modal-append-to-body
			title="选择"
			width="800px"
			@close="cancel"
			@open="onOpenDialog"
			:close-on-click-modal="false"
		>
			<t-auditer
				:disDept="disDept"
				:disUser="disUser"
				:multiple="multiple"
				:disabled="disabled"
				:visible="visible"
				ref="auditer"
				v-model="returnValue"
				:authFlag="authFlag"
			></t-auditer>
			<template #footer>
				<el-button type="danger" @click="cancel">取消</el-button>
				<el-button type="success" @click="confirm">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import request from "@/common/request"
import TAuditer from "./auditer.vue"

export default {
	name: "v-auditer",
	model: {
		prop: "value",
		event: "update:value",
	},
	props: {
		value: {
			type: [Object],
		},
		disabled: {
			type: [Boolean, Function, Array],
			default: false,
		},
		disDept: {
			type: [Boolean],
			default: false,
		},
		disUser: {
			type: [Boolean],
			default: false,
		},
		multiple: {
			type: [Boolean],
			default: true,
		},
		authFlag: {
			type: String,
			default: "01",
		},
	},
	data() {
		return {
			visible: false,
			valueName: "",
			checkList: [],
		}
	},
	computed: {
		returnValue: {
			get() {
				return {
					dept: [],
					user: [],
					...this.value,
				}
			},
			set(value) {
				this.$emit("update:value", value)
			},
		},
	},
	methods: {
		cancel() {
			this.$refs.auditer.refresh()
			this.visible = false
		},
		confirm() {
			this.returnValue = this.formatReturnValue()
			this.checkList = [...this.$refs.auditer.checkList]
			this.valueName = this.$refs.auditer.checkList.map(item => item.name).join(",")
			this.$emit("on-confirm", this.returnValue, this.$refs.auditer.checkList)
			this.cancel()
		},

		open() {
			if (typeof this.disabled === "boolean") {
				if (this.disabled) return
			}
			this.visible = true
		},

		formatReturnValue() {
			const dept = []
			const user = []
			this.$refs.auditer.checkList.forEach(item => {
				if (item.type === "00") {
					dept.push(item.id)
				} else {
					user.push(item.id)
				}
			})
			return {
				dept,
				user,
			}
		},
		onOpenDialog() {
			this.$nextTick(() => {
				this.$refs.auditer.checkList = [].concat(this.checkList)
			})
		},
		async getCheackList() {
			const { code, data } = await request("post", "/system/sysDept/nameForCom", this.returnValue)
			if (code == 0) {
				this.checkList = [].concat(data)
				this.valueName = this.checkList.map(item => item.name).join(",")
			}
		},
	},
	watch: {
		value: {
			handler() {
				this.getCheackList()
			},
			immediate: true,
			deep: true,
		},
	},
	components: {
		TAuditer,
	},
}
</script>

<style lang="scss" scoped></style>
